package com.kang.auth.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.kang.auth.service.AuthService;
import com.kang.utils.JwtUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class AuthServiceImpl implements AuthService {

	private static final Logger logger = LoggerFactory.getLogger(AuthServiceImpl.class);

	@Autowired
	private StringRedisTemplate redisTemplate;

	private static final String FIXED_KEY = "202cb962ac59075b964b07152d234b70";
	private static final String REDIS_KEY_PREFIX = "login-token:";
	private static final long TOKEN_EXPIRATION_TIME = 3600; // 1 hour in seconds

	@Override
	public String auth(String username, String password) {
		try {
			// Hash the password
			String hashedPassword = SecureUtil.md5(password);

			// Validate username and password
			if ("linkang".equals(username) && FIXED_KEY.equals(hashedPassword)) {
				// Generate a UUID
				String uuid = UUID.randomUUID().toString();

				// Store the token in Redis with an expiration time
				String redisKey = REDIS_KEY_PREFIX + uuid;
				redisTemplate.opsForValue().set(redisKey, username, TOKEN_EXPIRATION_TIME, TimeUnit.SECONDS);

				// Create data for JWT
				Map<String, Object> claims = new HashMap<>();
				claims.put("username", username);
				claims.put("token", uuid);

				// Generate JWT token
				String token = JwtUtils.createToken(claims);

				logger.info("Authentication successful for user: {}", username);
				return token;
			} else {
				logger.warn("Authentication failed: Invalid username or password.");
				return null;
			}
		} catch (Exception e) {
			logger.error("Error during authentication", e);
			return null;
		}
	}
}
